package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 保存菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        log.info("执行新增菜品操作, dishDto = {}", dishDto.toString());
        dishService.saveDishWithFlavors(dishDto);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success();
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(@RequestParam(required = false, defaultValue = "1") Integer page,
                        @RequestParam(required = false, defaultValue = "10") Integer pageSize, String name) {
        log.info("执行分页查询, page={}, pageSize={}, name={}", page, pageSize, name);

        //分页参数
        Page<Dish> pageInfo = new Page<>(page, pageSize);

        //查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo, lambdaQueryWrapper);


        // ------------------------------> 完善categoryName
        Page<DishDto> dishDtoPage = new Page<>();
        dishDtoPage.setTotal(pageInfo.getTotal());//total 总记录数

        List<Dish> dishList = pageInfo.getRecords();
        List<DishDto> dishDtoList = dishList.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto); //dish ---> dishDto ;

            //封装categoryName;
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());

        /*
        List<DishDto> dishDtoList  = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto); //dish ---> dishDto ;
            //封装categoryName;
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            dishDtoList.add(dishDto);
        }
        */

        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);//total, records
    }


    /**
     * 根据ID查询菜品及口味数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        if (dishDto != null) {
            return R.success(dishDto);
        }
        return R.error("未查询到菜品");
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        log.info("更新菜品, dishDto={}", dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);


        return R.success();
    }


    /**
     * 根据分类ID查询菜品列表
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        log.info("查询菜品数据, dish={}",dish.toString());

        //组装查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId() );
        lambdaQueryWrapper.eq(Dish::getStatus,1);//启售状态
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行查询
        List<Dish> dishList = dishService.list(lambdaQueryWrapper);

        //返回查询结果
        return R.success(dishList);
    }*/


    /**
     * 根据分类ID查询菜品列表
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        log.info("查询菜品数据, dish={}", dish.toString());
        List<DishDto> dishDtos = null;
        //动态获取key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //从redis中获取缓存数据
        dishDtos= (List<DishDto>) redisTemplate.opsForValue().get(key);

        //如果存在,直接返回成果的结果
        if (dishDtos !=null){
           return R.success(dishDtos);
        }


            //组装查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        lambdaQueryWrapper.eq(Dish::getStatus, 1);//启售状态
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行查询
        List<Dish> dishList = dishService.list(lambdaQueryWrapper);


        //组装数据, 完善功能 ---------> List<DishDto>
        List<DishDto> dishDtoList = dishList.stream().map(dish1 -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1, dishDto);

            //封装categoryName
            Category category = categoryService.getById(dish1.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }

            //封装flavors
            LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            flavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dish1.getId());
            List<DishFlavor> flavors = dishFlavorService.list(flavorLambdaQueryWrapper);
            dishDto.setFlavors(flavors);

            return dishDto;
        }).collect(Collectors.toList());


        //不存在,将查询结果缓存到redis中
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        //返回查询结果
        return R.success(dishDtoList);
    }


    //-------------------------------------------------- 实战功能 ----------------------

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}", ids);

        dishService.removeWithFlavors(ids);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("菜品数据删除成功");
    }


    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;


    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        // 1). 判断: 如果 停售的菜品 关联了 在售的套餐 是不允许的, 需要提示错误信息
        if (status == 0) {//停售
            //dish_id  ----------> setmeal_id
            LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishLambdaQueryWrapper.in(SetmealDish::getDishId, ids);
            List<SetmealDish> dishList = setmealDishService.list(setmealDishLambdaQueryWrapper);

            if (!CollectionUtils.isEmpty(dishList)) {
                //这批次菜品关联的套餐ID集合
                List<Long> setmealIds = dishList.stream().map(setmealDish -> {
                    return setmealDish.getSetmealId();
                }).collect(Collectors.toList());

                LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
                setmealLambdaQueryWrapper.in(Setmeal::getId, setmealIds);
                setmealLambdaQueryWrapper.eq(Setmeal::getStatus, 1);

                int count = setmealService.count(setmealLambdaQueryWrapper);
                if (count > 0) {
                    throw new CustomException("停售的菜品 关联了 在售的套餐, 请先停售套餐");
                }
            }
        }

        // 2). 批量修改菜品的状态
        List<Dish> dishList = dishService.listByIds(ids);
        dishList.stream().forEach(dish -> {
            dish.setStatus(status);
        });
        dishService.updateBatchById(dishList);

        return R.success();
    }


}
